<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\analysis\stat\account;

use app\enum\CdcEnum;
use app\enum\CommonEnum;
use app\enum\ServiceCostEnum;
use app\model\mongo\MongoReportModel;
use app\model\mongo\MongoStatModel;
use app\model\mongo\MongoSyncModel;
use app\service\analysis\stat\StatInterface;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class OceanAccountService extends AccountStatService implements StatInterface
{
    protected ?MongoSyncModel $syncModel;

    protected ?MongoStatModel $statModel;

    protected ?MongoReportModel $recordModel;

    protected int $mediaId = CommonEnum::OE_MEDIA;

    protected array $statModelList = [
        CdcEnum::STAT_CLIENT => '\app\model\mongo\MongoClientAccountTypeDayStatModel',
        CdcEnum::STAT_PRODUCT => '\app\model\mongo\MongoProductAccountTypeDayStatModel',
        CdcEnum::STAT_MONTH => '\app\model\mongo\MongoClientMonthStatModel',
        CdcEnum::STAT_CLIENT_MEDIA => '\app\model\mongo\MongoClientMediaMonthStatModel',
    ];

    protected array $recordModelList = [
        CdcEnum::STAT_CLIENT => '\app\model\mongo\MongoOeAccountDayReportModel',
        CdcEnum::STAT_PRODUCT => '\app\model\mongo\MongoOeAccountDayReportModel',
        CdcEnum::STAT_MONTH => '\app\model\mongo\MongoOeAccountDayReportModel',
        CdcEnum::STAT_CLIENT_MEDIA => '\app\model\mongo\MongoOeAccountDayReportModel',
    ];

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public function runStat(MongoSyncModel $model): bool
    {
        $this->syncModel = $model;
        $lockKey = sprintf(ServiceCostEnum::CACHE_CONFIG['media_account_cost_lock'][CommonEnum::OE_MEDIA], strval($this->syncModel->getKey()));
        if (self::lock($lockKey, 1, 120)) {
            if (! $this->setModel()) {
                return false;
            }

            $type = $this->compareStat();
            if ($type == -1) {
                if (! $this->addStatByRecord()) {
                    return false;
                }
            } else {
                if (! $this->sumStat()) {
                    return false;
                }
            }

            return true;
        }

        return self::setError('加锁失败！lock_key:' . $lockKey);
    }

    /**
     * 获取消耗.
     * @return mixed
     */
    public function getCost()
    {
        return $this->recordModel->getAttr('cost');
    }
}
